package org.jeecg.modules.system.upgrade.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xkcoding.http.util.StringUtil;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.system.upgrade.dto.EditionDto;
import org.jeecg.modules.system.upgrade.dto.InsertEditionDto;
import org.jeecg.modules.system.upgrade.dto.VersionDto;
import org.jeecg.modules.system.upgrade.entity.BikeUpgradeApp;
import org.jeecg.modules.system.upgrade.entity.BikeUpgradeAppPackage;
import org.jeecg.modules.system.upgrade.entity.BikeUpgradeAppUpgrade;
import org.jeecg.modules.system.upgrade.entity.BikeUpgradeAppVersion;
import org.jeecg.modules.system.upgrade.mapper.BikeUpgradeAppMapper;
import org.jeecg.modules.system.upgrade.mapper.BikeUpgradeAppPackageMapper;
import org.jeecg.modules.system.upgrade.mapper.BikeUpgradeAppUpgradeMapper;
import org.jeecg.modules.system.upgrade.mapper.BikeUpgradeAppVersionMapper;
import org.jeecg.modules.system.upgrade.service.IBikeUpgradeAppVersionService;
import org.jeecg.modules.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * @Description: APP版本表
 * @Author: 月月鸟
 * @Date:   2021-07-14
 * @Version: V1.0
 */
@Service
public class BikeUpgradeAppVersionServiceImpl extends ServiceImpl<BikeUpgradeAppVersionMapper, BikeUpgradeAppVersion> implements IBikeUpgradeAppVersionService {


    @Autowired
    private BikeUpgradeAppMapper bikeUpgradeAppMapper;
    @Autowired
    private BikeUpgradeAppPackageMapper bikeUpgradeAppPackageMapper;
    @Autowired
    private BikeUpgradeAppUpgradeMapper bikeUpgradeAppUpgradeMapper;
    @Autowired
    private BikeUpgradeAppVersionMapper bikeUpgradeAppVersionMapper;


    /**
     * 查询版本列表
     * @param newest 是否最新版本
     * @return
     */
    @Override
    public IPage<VersionDto> getEditionList(String id,String newest,String appId,Integer pageNo,Integer pageSize) {
        Page<EditionDto> page = new Page<>(pageNo, pageSize);
        IPage<VersionDto> editionList = bikeUpgradeAppVersionMapper.getEditionList(page, appId, id, newest);
        for (VersionDto versionDto : editionList.getRecords()) {
            if (!StringUtils.isEmpty(versionDto.getNewYn())) {
                versionDto.setNewest(1);
            } else {
                versionDto.setNewest(0);
            }
        }
        return editionList;
    }
    /**
     * 根据类型以及是否最新查询下载路径
     */
    @Override
    public VersionDto getProgram(String newest, String appId) {

        Page<EditionDto> page = new Page<>(1, 10);
        String id = null;
        IPage<VersionDto> editionList = bikeUpgradeAppVersionMapper.getEditionList(page, appId, id, newest);
        List<VersionDto> records = editionList.getRecords();
        if (records.isEmpty()){
            return null ;
        }
        for (VersionDto versionDto : editionList.getRecords()) {
            if (!StringUtils.isEmpty(versionDto.getNewYn())) {
                versionDto.setNewest(1);
            } else {
                versionDto.setNewest(0);
            }
        }

        return records.get(0);
    }
    @Override
    public Result<?> insertEdition(InsertEditionDto insertEditionDto) {
        if (!checkVersion(insertEditionDto.getAppId(), insertEditionDto.getVersion())){
            return Result.error("版本号重复");
        }
        //新增文件
        BikeUpgradeAppPackage bikeUpgradeAppPackage = new BikeUpgradeAppPackage();
        //新增版本
        BikeUpgradeAppVersion bikeUpgradeAppVersion = new BikeUpgradeAppVersion();

        if (insertEditionDto.getAppId().equals("100004")){
            String CheckCode = MD5Utils.bytesToMd5String(insertEditionDto.getContent());
            if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                return Result.error("校验码未通过");
            }
        }else if (insertEditionDto.getAppId().equals("100005")){
            String CheckCode = MD5Utils.bytesToMd5PileString(insertEditionDto.getContent());
            if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                return Result.error("校验码未通过");
            }
        }

        //新增版本
        String uuid = UUID.randomUUID().toString();
        bikeUpgradeAppVersion.setId(uuid);
        bikeUpgradeAppVersion.setAppId(insertEditionDto.getAppId());
        bikeUpgradeAppVersion.setVersion(insertEditionDto.getVersion());
        bikeUpgradeAppVersion.setIsForce(insertEditionDto.getIsForce());
        if (StringUtil.isNotEmpty(insertEditionDto.getCheckCode()))
            bikeUpgradeAppVersion.setCheckCode(insertEditionDto.getCheckCode());
        bikeUpgradeAppVersion.setMemo(insertEditionDto.getMemo());
        int insert = bikeUpgradeAppVersionMapper.insert(bikeUpgradeAppVersion);
        //新增文件

        bikeUpgradeAppPackage.setAppId(insertEditionDto.getAppId());
        bikeUpgradeAppPackage.setVersionId(uuid);
        bikeUpgradeAppPackage.setFileName(insertEditionDto.getFileName());
        //bikeUpgradeAppPackage.setFileSize(insertEditionDto.getFileSize());
        //bikeUpgradeAppPackage.setFileType(insertEditionDto.getFileType());
        bikeUpgradeAppPackage.setDownloadUrl(insertEditionDto.getDownloadUrl());
        if (insertEditionDto.getAppId().equals("100004")||insertEditionDto.getAppId().equals("100005")){
            //判断是否是网点或车桩程序
            bikeUpgradeAppPackage.setFileData(insertEditionDto.getContent());
        }
        bikeUpgradeAppPackageMapper.insert(bikeUpgradeAppPackage);
        //bikeUpgradeAppPackageMapper.insertUpgradePackage(bikeUpgradeAppPackage);
        return Result.OK("新增成功");


    }

    private boolean checkVersion(String appId, String version) {
        Integer selectCount = bikeUpgradeAppVersionMapper.selectCount(new QueryWrapper<BikeUpgradeAppVersion>()
                .eq("app_id", appId)
                .eq("version", version)
        );
        return selectCount == 0;
    }

    @Override
    public Result<?> updateEdition(InsertEditionDto insertEditionDto) {
        if (!checkVersionOutIs(insertEditionDto.getAppId(), insertEditionDto.getVersion(),insertEditionDto.getVesId())){
            return Result.error("版本号重复");
        }
        if (insertEditionDto.getAppId().equals("100004")){
            if (StringUtils.isEmpty(insertEditionDto.getContent())){
                BikeUpgradeAppPackage bikeUpgradeAppPackage = bikeUpgradeAppPackageMapper.selectById(insertEditionDto.getPaId());
                String CheckCode = MD5Utils.bytesToMd5String(bikeUpgradeAppPackage.getFileData());
                if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                    return Result.error("校验码未通过");
                }
            }else {
                String CheckCode = MD5Utils.bytesToMd5String(insertEditionDto.getContent());
                if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                    return Result.error("校验码未通过");
                }
            }
        }else if (insertEditionDto.getAppId().equals("100005")){
            if (StringUtils.isEmpty(insertEditionDto.getContent())){
                BikeUpgradeAppPackage bikeUpgradeAppPackage = bikeUpgradeAppPackageMapper.selectById(insertEditionDto.getPaId());
                String CheckCode = MD5Utils.bytesToMd5PileString(bikeUpgradeAppPackage.getFileData());
                if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                    return Result.error("校验码未通过");
                }
            }else {
                String CheckCode = MD5Utils.bytesToMd5PileString(insertEditionDto.getContent());
                if (!insertEditionDto.getCheckCode().equals(CheckCode)){
                    return Result.error("校验码未通过");
                }
            }
        }
        //修改版本
        BikeUpgradeAppVersion bikeUpgradeAppVersion = new BikeUpgradeAppVersion();
        bikeUpgradeAppVersion.setId(insertEditionDto.getVesId());
        bikeUpgradeAppVersion.setVersion(insertEditionDto.getVersion());
        bikeUpgradeAppVersion.setIsForce(insertEditionDto.getIsForce());
        if (StringUtil.isNotEmpty(insertEditionDto.getCheckCode()))
            bikeUpgradeAppVersion.setCheckCode(insertEditionDto.getCheckCode());
        bikeUpgradeAppVersion.setMemo(insertEditionDto.getMemo());
        int insert = bikeUpgradeAppVersionMapper.updateById(bikeUpgradeAppVersion);

        //修改文件
        BikeUpgradeAppPackage bikeUpgradeAppPackage = new BikeUpgradeAppPackage();
        bikeUpgradeAppPackage.setId(insertEditionDto.getPaId());
        bikeUpgradeAppPackage.setFileName(insertEditionDto.getFileName());
        bikeUpgradeAppPackage.setFileSize(insertEditionDto.getFileSize());
        bikeUpgradeAppPackage.setFileType(insertEditionDto.getFileType());
        bikeUpgradeAppPackage.setDownloadUrl(insertEditionDto.getDownloadUrl());
        //判断是否是网点或车桩程序
        if (insertEditionDto.getAppId().equals("100004")||insertEditionDto.getAppId().equals("100005")){
            bikeUpgradeAppPackage.setFileData(insertEditionDto.getContent());
        }
        int insert1 = bikeUpgradeAppPackageMapper.updateById(bikeUpgradeAppPackage);
        if (insert==1 && insert1== 1){
            return Result.OK("修改成功");
        }
        return Result.error("修改失败");

    }

    private boolean checkVersionOutIs(String appId, String version, String versionId) {
        Integer selectCount = bikeUpgradeAppVersionMapper.selectCount(new QueryWrapper<BikeUpgradeAppVersion>()
                .eq("app_id", appId)
                .eq("version", version)
                .ne("id",versionId)
        );
        return selectCount == 0;
    }

    /**
     * 查看下载记录
     */
    @Override
    public Result<?> downRecord(String versionId,Integer pageNo, Integer pageSize) {

        Page<BikeUpgradeAppUpgrade> page= new Page(pageNo,pageSize);
        Page<BikeUpgradeAppUpgrade> bikeUpgradeAppUpgradePage=null;
        if (StringUtils.isEmpty(versionId)){
           bikeUpgradeAppUpgradePage = bikeUpgradeAppUpgradeMapper.selectPage(page, null);

        }else {
            bikeUpgradeAppUpgradePage = bikeUpgradeAppUpgradeMapper.selectPage(page, new QueryWrapper<BikeUpgradeAppUpgrade>().eq("version_id",versionId));
        }
        //循环插入版本号
        bikeUpgradeAppUpgradePage.getRecords().forEach(
                vs->{
                    BikeUpgradeAppVersion bikeUpgradeAppVersion = bikeUpgradeAppVersionMapper.selectOne(new QueryWrapper<BikeUpgradeAppVersion>().eq("id",vs.getVersionId()));
                    vs.setVersion(bikeUpgradeAppVersion.getVersion());
                }
        );
        return Result.OK(bikeUpgradeAppUpgradePage);
    }

    @Override
    public Result<?> deleteEdition(String versionId) {
        BikeUpgradeApp ves = bikeUpgradeAppMapper.selectOne(new QueryWrapper<BikeUpgradeApp>().eq("version_id", versionId));
        if (ves!=null){
            return Result.error("当前版本不可删除");
        }

        bikeUpgradeAppVersionMapper.deleteById(versionId);
        bikeUpgradeAppPackageMapper.delete(new QueryWrapper<BikeUpgradeAppPackage>().eq("version_id", versionId));

        return Result.OK("删除成功");
    }

    @Override
    public Result<?> updateApp(EditionDto editionDto) {
        BikeUpgradeApp  bikeUpgradeApp = new BikeUpgradeApp();
        bikeUpgradeApp.setId(editionDto.getAppId());
        bikeUpgradeApp.setVersionId(editionDto.getId());
        BikeUpgradeAppVersion bikeUpgradeAppVersion = bikeUpgradeAppVersionMapper.selectById(editionDto.getId());
        if (bikeUpgradeAppVersion!=null){
            bikeUpgradeAppVersion.setReleaseTime(new Date());
            bikeUpgradeAppVersionMapper.updateById(bikeUpgradeAppVersion);
        }
        int i = bikeUpgradeAppMapper.updateById(bikeUpgradeApp);

        return Result.OK("切换成功");
    }

}
